﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Sales;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Hr;
using ESOL.WinUI.Bpt;
using ESOL.WinUI.Pur;

namespace ESOL.WinUI.Sales
{
    public partial class frmMaintainSalesOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public SalesOrderEntity SelectedSalesOrder { get; set; }
        public SalesOrderItemEntity Selectorderitem { get; set; }//+
        private List<SalesOrderItemEntity> DeleteList = new List<SalesOrderItemEntity>();
        private List<SalesProdPlanApplicationItemEntity> mListApplicationItems;
        private List<SalesProdPlanApplicationEntity> mListApplications;
        private SalesContractDetailNewEntity mSalesContractDetail;
        private decimal dTotalPrice;
        #endregion

        #region Constructor
        public frmMaintainSalesOrder()
        {
            
            InitializeComponent();
            if (SelectedSalesOrder == null)
            {
                SelectedSalesOrder = new SalesOrderEntity();
                SelectedSalesOrder.OrderId = Guid.NewGuid().ToString();
            }
        }
        public frmMaintainSalesOrder(List<SalesProdPlanApplicationItemEntity> list, MstCustomerEntity customer)
        {
            InitializeComponent();
            if (SelectedSalesOrder == null)
            {
                SelectedSalesOrder = new SalesOrderEntity();
                SelectedSalesOrder.OrderId = Guid.NewGuid().ToString();
            }
            SetFieldsByCustomer(customer);
            mListApplicationItems = list;
        }
        #endregion

        #region Functions
        private void SetFieldsByCustomer(MstCustomerEntity customer)
        {
            if (customer != null)
            {
                txtCustomer.Tag = customer;
                txtCustomer.Text = customer.CustomerName;
                UICommonFunctions.BindContactCombobox(cmbCustomerContact, customer.CustomerId, false);
                UICommonFunctions.BindContactGridCombobox(colCONTACT_ID, customer.CustomerId, true);
            }
            else
            {
                txtCustomer.Tag = null;
                txtCustomer.Text = "";
                UICommonFunctions.BindContactCombobox(cmbCustomerContact, "", false);
                UICommonFunctions.BindContactGridCombobox(colCONTACT_ID, "", true);
                txtCustomerContactPhone.Text = "";
            }
        }

        private void SetSalesOrderByQuoteOrder(SalesQuoteOrderEntity quoteOrder)
        {
            if (quoteOrder == null)
            {
                return;
            }
            if (SelectedSalesOrder == null)
            {
                SelectedSalesOrder = new SalesOrderEntity();
                SelectedSalesOrder.OrderId = Guid.NewGuid().ToString();
            }
            SelectedSalesOrder.QuoteOrderId = quoteOrder.QuoteOrderId;
            SelectedSalesOrder.SupplierId = quoteOrder.SupplierId;
            SelectedSalesOrder.CustomerId = quoteOrder.CustomerId;
            SelectedSalesOrder.OrderDepartment = quoteOrder.QuoteDepartment;
            SelectedSalesOrder.OrderPerson = quoteOrder.QuotePerson;
            SelectedSalesOrder.Currency = quoteOrder.Currency;
            SelectedSalesOrder.TransportType = quoteOrder.TransportType;
            SelectedSalesOrder.PackageType = quoteOrder.PackageType;
            SelectedSalesOrder.OrderDate = DateTime.Today;
            SelectedSalesOrder.PaymentType = quoteOrder.PaymentType;
            SelectedSalesOrder.IsTax = quoteOrder.IsTax;
            SelectedSalesOrder.Attachment = quoteOrder.Attachment;
            

            ResetContactColumn();
            SetFields(false);

            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                if (dr.RowState != DataRowState.Added)
                {
                    SalesOrderItemEntity entity = new SalesOrderItemEntity(dr);
                    DeleteList.Add(entity);
                }
                dt.Rows.Remove(dr);
            }
            List<SalesQuoteItemEntity> list = SalesQuoteItemBs.GetByQuoteOrderID(quoteOrder.QuoteOrderId);
            foreach (SalesQuoteItemEntity entity in list)
            {
                DataRow dr = dt.NewRow();
                dr["ORDER_ITEM_ID"] = Guid.NewGuid().ToString();
                dr["ORDER_ID"] = SelectedSalesOrder.OrderId;
                dr["PRODUCT_ID"] = entity.ProductId;
                if (string.IsNullOrEmpty(entity.ProductId) == false)
                {
                    MstProductEntity mstProduct = MstProductBs.GetMstProductTypeByID(entity.ProductId);
                    if (mstProduct != null)
                    {
                        dr["PRODUCT_CODE"] = mstProduct.ProductCode;
                    }
                }
                dr["TAX_RATE"] = 0.17;
                dr["QTY"] = entity.Qty;
                dr["PRICE_NO_TAX"] = decimal.Round(entity.PriceNoTax, 2);
                dr["TOTAL_AMOUNT"] = decimal.Round(entity.Qty * entity.PriceNoTax, 2);
                dr["PRODUCT_SPEC_IN"] = entity.ProductSpecIn;
                dr["PRODUCT_SPEC_OUT"] = entity.ProductSpecOut;
                dr["MATERIAL"] = entity.Material;
                dr["DIAMETER_OUT"] = entity.DiameterOut;
                dr["DIAMETER_IN"] = entity.DiameterIn;
                dr["LENGTH"] = entity.Length;
                dr["UNIT"] = entity.Unit;
               

                dt.Rows.Add(dr);
            }
            ResetTotalAmount();
        }

        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbCurrency, "CS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "SALES", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbDeliveryWay, "DW", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPackageType, "PT", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPaymentType, "PAYWAY", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);
        }

        private void BindDataGridDetail()
        {
            if (SelectedSalesOrder == null)
            {
                gvMain.DataSource = null;
                return;
            }
            DataSet ds = SalesOrderItemBs.GetDataSetByOrderID(SelectedSalesOrder.OrderId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvMain.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvMain.DataSource = dt;
            DeleteList = new List<SalesOrderItemEntity>();
            ResetTotalAmount();
        }

        private void SetDataGridDetailByApplicationItems()
        {
            if (mListApplicationItems == null || mListApplicationItems.Count == 0)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            foreach (SalesProdPlanApplicationItemEntity entity in mListApplicationItems)
            {
                DataRow dr = dt.NewRow();
                entity.OrderItemId = Guid.NewGuid().ToString();
                dr["ORDER_ITEM_ID"] = entity.OrderItemId;
                dr["CONTACT_ID"] = entity.ContactId;
                dr["ORDER_ID"] = SelectedSalesOrder.OrderId;
                MstProductEntity product = MstProductBs.GetMstProductTypeByID(entity.ProductId);
                if (product != null)
                {
                    dr["PRODUCT_ID"] = product.ProductId;
                    dr["PRODUCT_CODE"] = product.ProductCode;
                    dr["SUGGEST_PRICE"] = decimal.Round(product.SuggestPrice, 2);
                }
                dr["PRODUCT_SPEC_IN"] = entity.ProductSpecIn;
                dr["PRODUCT_SPEC_OUT"] = entity.ProductSpecOut;
                dr["MATERIAL"] = entity.Material;
                dr["DIAMETER_OUT"] = entity.DiameterOut;
                dr["DIAMETER_IN"] = entity.DiameterIn;
                dr["LENGTH"] = entity.Length;
                dr["UNIT"] = entity.Unit;
                dr["QTY"] = entity.Qty;
                dr["TAX_RATE"] = 0.17;
                dr["PRICE_NO_TAX"] = decimal.Round(entity.Price, 2);
                if (cboxIsTax.Checked)
                {
                    dr["TOTAL_AMOUNT"] = decimal.Round(entity.Price * entity.Qty * (1 + CommonFunctions.ToDecimal(dr["TAX_RATE"])), 2);
                }
                else
                {
                    dr["TOTAL_AMOUNT"] = decimal.Round(entity.Price * entity.Qty, 2);
                }
                dr["APPLICATION_ITEM_ID"] = entity.ApplicationItemId;
                dt.Rows.Add(dr);
            }
            ResetTotalAmount();
        }

        private void SetFieldsByApplication()
        {
            if (mListApplicationItems == null || mListApplicationItems.Count == 0)
            {
                return;
            }
            string appId = mListApplicationItems[0].ApplicationId;
            SalesProdPlanApplicationEntity app = SalesProdPlanApplicationBs.GetSalesProdPlanApplicationByID(appId);
            if (app != null)
            {
                cmbDeliveryWay.SetSelectedValue(app.DeliveryType);
                cmbPaymentType.SetSelectedValue(app.PaymentType);
                dtpDeliveryDate.EditValue = SelectedSalesOrder.DeliveryDate;
            }
        }

        private void SetDataGridDetailByListBox()
        {

            if (lboxAppOrder.Tag == null || lboxAppOrder.Tag.GetType() != typeof(List<SalesProdPlanApplicationEntity>))
            {
                return;
            }
            List<SalesProdPlanApplicationItemEntity> mlistItems = new List<SalesProdPlanApplicationItemEntity>();
            List<SalesProdPlanApplicationEntity> mlist = (List<SalesProdPlanApplicationEntity>)lboxAppOrder.Tag;
            foreach (SalesProdPlanApplicationEntity entity in mlist)
            {
                List<SalesProdPlanApplicationItemEntity> items = SalesProdPlanApplicationItemBs.GetProdPlanApplicationItemByAppID(entity.ApplicationId);
                if (items != null && items.Count > 0)
                {
                    mlistItems.AddRange(items);
                }
            }
            mListApplications = mlist;
            mListApplicationItems = mlistItems;
            SetDataGridDetailByApplicationItems();
        }

        private void ResetTotalAmount()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            decimal totalAmount = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["PRICE_NO_TAX"].ToString()) == false
                    && string.IsNullOrEmpty(dr["PRICE_NO_TAX"].ToString()) == false)
                {
                    decimal price = CommonFunctions.ToDecimal(dr["PRICE_NO_TAX"].ToString());
                    decimal amount = CommonFunctions.ToDecimal(dr["QTY"].ToString()) * price;
                    dr["PRICE_NO_TAX"] = price.ToString("#0.00");
                    dr["TOTAL_AMOUNT"] = amount.ToString("#0.00");
                    totalAmount += amount;
                    dTotalPrice = decimal.Round(totalAmount, 2);
                    dr["TOTAL_AMOUNT"] = dTotalPrice;
                }
            }

        }

        private void ResetTax()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            decimal totalAmount = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["TOTAL_AMOUNT"] != null && CommonFunctions.IsDecimal(dr["TOTAL_AMOUNT"].ToString()))
                {
                    decimal tax = CommonFunctions.ToDecimal(dr["TAX_RATE"]) + 1;
                    decimal price = CommonFunctions.ToDecimal(dr["PRICE_NO_TAX"]);
                    if (cboxIsTax.Checked)
                    {
                        price = price * tax;
                    }
                    else
                    {
                        price = price / tax;
                    }
                    decimal amount = CommonFunctions.ToDecimal(dr["QTY"]) * price;
                    dr["PRICE_NO_TAX"] = price.ToString("#0.00");
                    dr["TOTAL_AMOUNT"] = amount.ToString("#0.00");
                    totalAmount += amount;
                }
            }
            dTotalPrice = decimal.Round(totalAmount, 2);
        }

        private void SetFields(bool refreshDetailGrid)
        {
            if (SelectedSalesOrder == null)
            {
                if (refreshDetailGrid)
                {
                    BindDataGridDetail();
                }
                return;
            }
            DataTable relations = SalesOrderToAppBs.GetDtByOrderId(SelectedSalesOrder.OrderId);
            if (relations != null && relations.Rows.Count > 0)
            {
                if (mListApplications != null)
                {
                    mListApplications.Clear();
                }
                else
                {
                    mListApplications = new List<SalesProdPlanApplicationEntity>();
                }
                lboxAppOrder.Items.Clear();
                foreach (DataRow dr in relations.Rows)
                {
                    SalesProdPlanApplicationEntity application = SalesProdPlanApplicationBs.GetSalesProdPlanApplicationByID(dr["APPLICATION_ID"].ToString());
                    if (application != null)
                    {
                        mListApplications.Add(application);
                        lboxAppOrder.Items.Add(application.ApplicationCode);
                    }
                }
                lboxAppOrder.Tag = mListApplications;
            }
            if (string.IsNullOrEmpty(SelectedSalesOrder.QuoteOrderId) == false)
            {
                SalesQuoteOrderEntity quoteOrder = SalesQuoteOrderBs.GetSalesQuoteOrderByID(SelectedSalesOrder.QuoteOrderId);
                if (quoteOrder != null)
                {
                    txtQuoteOrder.Text = quoteOrder.QuoteOrderCode;
                    txtQuoteOrder.Tag = quoteOrder;
                }
            }
            if (string.IsNullOrEmpty(SelectedSalesOrder.SupplierId) == false)
            {
                MstSupplierEntity supplier = MstSupplierBs.GetMstSupplierById(SelectedSalesOrder.SupplierId);
                if (supplier != null)
                {
                    txtSupplier.Tag = supplier;
                    txtSupplier.Text = supplier.SupplierName;
                    UICommonFunctions.BindSupplierContactCombobox(cmbSupplierContact, supplier.SupplierId, false);
                }
            }
            if (string.IsNullOrEmpty(SelectedSalesOrder.CustomerId) == false)
            {
                MstCustomerEntity customer = MstCustomerBs.GetMstCustomerByID(SelectedSalesOrder.CustomerId);
                if (customer != null)
                {
                    SetFieldsByCustomer(customer);
                }
            }
            txtOrderCode.Text = SelectedSalesOrder.OrderCode;
            dtpDeliveryDate.EditValue = SelectedSalesOrder.DeliveryDate;
            if (ThisActionType == ActionType.New)
            {
                MstPersonEntity person = MstPersonBs.GetMstPersonByID(CommonParameter.CurrentUser.PersonId);
                if (person != null)
                {
                    txtOrderPerson.Tag = person;
                    txtOrderPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                }
                if (SelectedSalesOrder.IsTax == 1)
                {
                    cboxIsTax.Checked = true;
                }
                else
                {
                    cboxIsTax.Checked = false;
                }
                dtpOrderDate.EditValue = DateTime.Today;
                dtpDeliveryDate.EditValue = "";
            }
            else
            {
                if (string.IsNullOrEmpty(SelectedSalesOrder.OrderPerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedSalesOrder.OrderPerson);
                    if (person != null)
                    {
                        txtOrderPerson.Tag = person;
                        txtOrderPerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
                if (string.IsNullOrEmpty(SelectedSalesOrder.ContactId) == false)
                {
                    cmbCustomerContact.SetSelectedValue(SelectedSalesOrder.ContactId);
                }
                //txtTotalAmount.Text = SelectedSalesOrder.TotalAmount.ToString("#0.00");
                cmbCurrency.SetSelectedValue(SelectedSalesOrder.Currency);
                cmbPaymentType.SetSelectedValue(SelectedSalesOrder.PaymentType);

                if (SelectedSalesOrder.IsTax == 1)
                {
                    cboxIsTax.Checked = true;
                }
                else
                {
                    cboxIsTax.Checked = false;
                }
                if (SelectedSalesOrder.IsEffective == 1)
                {
                    cboxIsEffective.Checked = true;
                }
                else
                {
                    cboxIsEffective.Checked = false;
                }
                cmbDeliveryWay.SetSelectedValue(SelectedSalesOrder.TransportType);
                cmbPackageType.SetSelectedValue(SelectedSalesOrder.PackageType);
                dtpOrderDate.EditValue = SelectedSalesOrder.OrderDate;
                cmbStatus.SetSelectedValue(SelectedSalesOrder.Status);
                txtAttachment.Text = SelectedSalesOrder.Attachment;
                txtRemark.Text = SelectedSalesOrder.Remark;
            }
          
            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedSalesOrder.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedSalesOrder.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedSalesOrder.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedSalesOrder.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedSalesOrder.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, SelectedSalesOrder.ApprovedBy);

            if (mListApplicationItems != null && mListApplicationItems.Count > 0)
            {
                if (mListApplications == null)
                {
                    mListApplications = new List<SalesProdPlanApplicationEntity>();
                }
                else
                {
                    mListApplications.Clear();
                }
                lboxAppOrder.Items.Clear();
                foreach (SalesProdPlanApplicationItemEntity item in mListApplicationItems)
                {
                    SalesProdPlanApplicationEntity app = SalesProdPlanApplicationBs.GetSalesProdPlanApplicationByItemID(item.ApplicationItemId);
                    
                    mListApplications.Add(app);
                    lboxAppOrder.Items.Add(app.ApplicationCode);
                }
                lboxAppOrder.Tag = mListApplications;

            }

            if (refreshDetailGrid)
            {
                BindDataGridDetail();
            }
        }

        private void SetEntity()
        {
            SelectedSalesOrder.OrderCode = txtOrderCode.Text;
            if (txtQuoteOrder.Tag != null && txtQuoteOrder.Tag.GetType() == typeof(SalesQuoteOrderEntity))
            {
                SelectedSalesOrder.QuoteOrderId = ((SalesQuoteOrderEntity)txtQuoteOrder.Tag).QuoteOrderId;
            }
            if (txtSupplier.Tag != null && txtSupplier.Tag.GetType() == typeof(MstSupplierEntity))
            {
                SelectedSalesOrder.SupplierId = ((MstSupplierEntity)txtSupplier.Tag).SupplierId;
            }
            if (txtCustomer.Tag != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                SelectedSalesOrder.CustomerId = ((MstCustomerEntity)txtCustomer.Tag).CustomerId;
            }
            if (dtpDeliveryDate.EditValue != null)
            {
                SelectedSalesOrder.DeliveryDate = Convert.ToDateTime(dtpDeliveryDate.EditValue);
            }
            if (txtOrderPerson.Tag != null && txtOrderPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedSalesOrder.OrderPerson = ((MstPersonEntity)txtOrderPerson.Tag).PersonId;
                MstDepartmentEntity mDepartment = MstDepartmentBs.GetMstDepartmentByID(((MstPersonEntity)txtOrderPerson.Tag).DepartmentId);
                if (mDepartment != null)
                {
                    SelectedSalesOrder.OrderDepartment = mDepartment.DepartmentId;
                }
            }
            if (cmbCustomerContact.SelectedValue != null && cmbCustomerContact.SelectedValue.ToString().Trim() != "")
            {
                SelectedSalesOrder.ContactId = cmbCustomerContact.SelectedValue.ToString().Trim();
            }
            SelectedSalesOrder.TotalAmount = dTotalPrice;
            if (cmbCurrency.SelectedValue != null && cmbCurrency.SelectedValue.ToString().Trim() != "")
            {
                SelectedSalesOrder.Currency = cmbCurrency.SelectedValue.ToString().Trim();
            }
            if (cmbPaymentType.SelectedValue != null && cmbPaymentType.SelectedValue.ToString().Trim() != "")
            {
                SelectedSalesOrder.PaymentType = cmbPaymentType.SelectedValue.ToString().Trim();
            }
            if (cboxIsTax.Checked)
            {
                SelectedSalesOrder.IsTax = 1;
            }
            else
            {
                SelectedSalesOrder.IsTax = 0;
            }
            if (cboxIsEffective.Checked)
            {
                SelectedSalesOrder.IsEffective = 1;
            }
            else
            {
                SelectedSalesOrder.IsEffective = 0;
            }
            if (cmbDeliveryWay.SelectedValue != null && cmbDeliveryWay.SelectedValue.ToString().Trim() != "")
            {
                SelectedSalesOrder.TransportType = cmbDeliveryWay.SelectedValue.ToString().Trim();
            }
            if (cmbPackageType.SelectedValue != null && cmbPackageType.SelectedValue.ToString().Trim() != "")
            {
                SelectedSalesOrder.PackageType = cmbPackageType.SelectedValue.ToString().Trim();
            }
            if (dtpOrderDate.EditValue != null)
            {
                SelectedSalesOrder.OrderDate = Convert.ToDateTime(dtpOrderDate.EditValue);
            }
            SelectedSalesOrder.Status = SalesStatus.SALES02.ToString();
            //SelectedSalesOrder.Attachment = txtAttachment.Text;
            SelectedSalesOrder.Remark = txtRemark.Text;

            if (ThisActionType == ActionType.New)
            {
                SelectedSalesOrder.CreatedDate = DateTime.Now;
                SelectedSalesOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedSalesOrder.LastModifiedDate = DateTime.Now;
                SelectedSalesOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
            GetContractInfoNew();
        }

        private bool CheckData()
        {
            //if (string.IsNullOrEmpty(txtOrderCode.Text))
            //{
            //    MessageBox.Show("订单号不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return false;
            //}
            if (string.IsNullOrEmpty(txtSupplier.Text))
            {
                MessageBox.Show("供应商不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtCustomer.Text))
            {
                MessageBox.Show("客户不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpDeliveryDate.EditValue.ToString().Equals("0001/1/1 0:00:00") || dtpDeliveryDate.EditValue == null)
            {
                MessageBox.Show("计划交期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtOrderPerson.Text))
            {
                MessageBox.Show("业务员不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbCurrency.SelectedValue == null || cmbCurrency.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("货币种类不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpOrderDate.EditValue == null)
            {
                MessageBox.Show("合同日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (gvMain.DataSource == null)
            {
                MessageBox.Show("订单明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt.Rows.Count == 0||dt==null)
            {
                MessageBox.Show("订单明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (UICommonFunctions.CheckDataGrid(gvMain) == false)
            {
                return false;
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = false;
                    if (mListApplicationItems != null && mListApplicationItems.Count > 0)
                    {
                        isSuccessful = SalesOrderBs.SaveOrder(true, SelectedSalesOrder, dt, DeleteList, mListApplicationItems, mSalesContractDetail,mListApplications);
                    }
                    else
                    {
                        isSuccessful = SalesOrderBs.SaveOrder(true, SelectedSalesOrder, dt, DeleteList, mSalesContractDetail,mListApplications);
                    }
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = SalesOrderBs.SaveOrder(false, SelectedSalesOrder, dt, DeleteList, mSalesContractDetail,mListApplications);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SelectedSalesOrder.ApprovedDate = DateTime.Now;
                    SelectedSalesOrder.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = SalesOrderBs.UpdateSalesOrder(SelectedSalesOrder);
                    //CreateProductPlanApplication();
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        /// <summary>
        /// 自动生成生产计划申请单
        /// </summary>
        /// <returns></returns>
        //private bool CreateProductPlanApplication()
        //{
        //    SalesProdPlanApplicationEntity salesProdPlanApplication = new SalesProdPlanApplicationEntity();
        //    salesProdPlanApplication.ApplicationId = Guid.NewGuid().ToString();
        //    salesProdPlanApplication.ApprovedDate = DateTime.Now;
        //    salesProdPlanApplication.OrderId = SelectedSalesOrder.OrderId;
        //    salesProdPlanApplication.CustomerId = SelectedSalesOrder.CustomerId;
        //    salesProdPlanApplication.ContactId = SelectedSalesOrder.ContactId;
        //    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedSalesOrder.CreatedBy);
        //    salesProdPlanApplication.DepartmentId = person.DepartmentId;
        //    salesProdPlanApplication.ApplicationPerson = person.PersonId;
        //    salesProdPlanApplication.ApplicationDate = DateTime.Now;
        //    salesProdPlanApplication.PaymentType = SelectedSalesOrder.PaymentType;
        //    salesProdPlanApplication.DeliveryDate = SelectedSalesOrder.DeliveryDate;
        //    salesProdPlanApplication.TrasportType = SelectedSalesOrder.TransportType;
        //    salesProdPlanApplication.DeliveryType = "DW01";
        //    salesProdPlanApplication.TotalAmount = SelectedSalesOrder.TotalAmount;
        //    salesProdPlanApplication.IsTax = SelectedSalesOrder.IsTax;
        //    salesProdPlanApplication.CreatedBy = Common.CommonParameter.CurrentUser.PersonId;
        //    salesProdPlanApplication.CreatedDate = DateTime.Now;
        //    salesProdPlanApplication.LastModifiedBy = Common.CommonParameter.CurrentUser.PersonId;
        //    salesProdPlanApplication.LastModifiedDate = DateTime.Now;
        //    salesProdPlanApplication.Status = "STATUS01";
        //    salesProdPlanApplication.Remark = SelectedSalesOrder.Remark;

        //    DataTable dt = new DataTable();
        //    dt.Columns.Add("APPLICATION_ITEM_ID", typeof(string));
        //    dt.Columns.Add("APPLICATION_ID", typeof(string));
        //    dt.Columns.Add("CONTACT_ID", typeof(string));
        //    dt.Columns.Add("PRODUCT_ID", typeof(string));
        //    dt.Columns.Add("REQUIRED_DELIVERY_DATE", typeof(DateTime));
        //    dt.Columns.Add("LOCATION_CODE", typeof(string));
        //    dt.Columns.Add("QTY", typeof(decimal));
        //    dt.Columns.Add("PRICE", typeof(decimal));
        //    dt.Columns.Add("PRICE_TYPE", typeof(string));
        //    dt.Columns.Add("PRODUCT_TYPE", typeof(string));
        //    dt.Columns.Add("BLUEPRINT_START_DATE", typeof(DateTime));
        //    dt.Columns.Add("BLUEPRINT_END_DATE", typeof(DateTime));
        //    dt.Columns.Add("PACKAGE_TYPE", typeof(string));
        //    dt.Columns.Add("CHECKING_TYPE", typeof(string));
        //    dt.Columns.Add("PRINT_BRAND", typeof(int));
        //    dt.Columns.Add("IS_FINISHED", typeof(int));
        //    dt.Columns.Add("DELIVERY_APPLICATION", typeof(string));
        //    dt.Columns.Add("DELIVERY_QTY", typeof(decimal));
        //    dt.Columns.Add("STATUS", typeof(string));
        //    dt.Columns.Add("REMARK", typeof(string));
        //    dt.Columns.Add("PRODUCT_SPEC_IN", typeof(string));
        //    dt.Columns.Add("PRODUCT_SPEC_OUT", typeof(string));
        //    dt.Columns.Add("MATERIAL", typeof(string));
        //    dt.Columns.Add("DIAMETER_OUT", typeof(decimal));
        //    dt.Columns.Add("DIAMETER_IN", typeof(decimal));
        //    dt.Columns.Add("LENGTH", typeof(decimal));
        //    dt.Columns.Add("UNIT", typeof(string));
        //    dt.Columns.Add("ORDER_ITEM_ID", typeof(string));
        //    dt.Columns.Add("REGISTER_ITEM_ID", typeof(string));

        //    DataTable dtSalesOrderItem =  gvMain.DataSource as DataTable;
        //    foreach (DataRow drSalesOrderItem in dtSalesOrderItem.Rows)
        //    {
        //        DataRow dr = dt.NewRow();
        //        dr["APPLICATION_ITEM_ID"] = Guid.NewGuid().ToString();
        //        dr["APPLICATION_ID"] = salesProdPlanApplication.ApplicationId;
        //        if (drSalesOrderItem["PRODUCT_ID"] != null || string.IsNullOrEmpty(drSalesOrderItem["PRODUCT_ID"].ToString()) == false)
        //        {
        //            dr["PRODUCT_ID"] = drSalesOrderItem["PRODUCT_ID"];
        //        }
        //        dr["CONTACT_ID"] = drSalesOrderItem["CONTACT_ID"];
        //        dr["QTY"] = drSalesOrderItem["QTY"];
        //        dr["PRICE"] = drSalesOrderItem["PRICE_NO_TAX"];
        //        dr["PRINT_BRAND"] = 0;
        //        dr["IS_FINISHED"] = 0;
        //        dr["DELIVERY_QTY"] = 0;
        //        dr["STATUS"] = "PASTATUS01";
        //        dr["PRODUCT_SPEC_OUT"] = drSalesOrderItem["PRODUCT_SPEC_OUT"];
        //        dr["MATERIAL"] = drSalesOrderItem["MATERIAL"];
        //        dr["UNIT"] = drSalesOrderItem["UNIT"];
        //        dr["LOCATION_CODE"] = drSalesOrderItem["SIZE"];
        //        dt.Rows.Add(dr);
        //    }
        //    List<SalesProdPlanApplicationItemEntity> listDel = new List<SalesProdPlanApplicationItemEntity>();
        //    return SalesProdPlanApplicationBs.SaveProdPlanApplication(true, salesProdPlanApplication, dt, listDel,mListOrder);
        //}

        private void ResetContactColumn()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                dr["CONTACT_ID"] = null;
            }
        }

        private bool UploadAttached(string fileFullName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileFullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        SelectedSalesOrder.Attachment = SelectedSalesOrder.OrderCode + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + CommonFunctions.GetFileExtension(fileFullName);
                        string path = service.SalesOrderAttachedPath();
                        byte[] bytes = CommonFunctions.FileToByte(fileFullName);
                        string errMsg = "";
                        bool result = service.UploadFileNew(bytes, path + "\\" + SelectedSalesOrder.Attachment, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        result = SalesOrderBs.UpdateSalesOrder(SelectedSalesOrder);
                        if (result)
                        {
                            txtAttachment.Text = SelectedSalesOrder.Attachment;
                        }
                        return result;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private bool DownloadAttached(string fileFullName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileFullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        string errMsg = "";
                        string path = service.SalesOrderAttachedPath();
                        byte[] bytes = service.DownloadFileNew(path + "\\" + SelectedSalesOrder.Attachment, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        Image image = CommonFunctions.byteArrayToImage(bytes);
                        image.Save(fileFullName);
                        image.Dispose();
                        return true;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void SetContractInfoFields()
        {
            //if (SelectedSalesOrder == null || string.IsNullOrEmpty(SelectedSalesOrder.OrderId))
            //{
            //    return;
            //}
            //lblTax.Visible = cboxIsTax.Checked;
            //txtDetailAmount.Text = SelectedSalesOrder.TotalAmount.ToString("#0.00");
            //MstCustomerEntity supplier = MstCustomerBs.GetMstCustomerByID(SelectedSalesOrder.SupplierId);
            //MstCustomerEntity customer = MstCustomerBs.GetMstCustomerByID(SelectedSalesOrder.CustomerId);
            //if (supplier != null)
            //{
            //    txtCSFullName.Text = supplier.CustomerFullName;
            //    txtCSAddress.Text = supplier.Address;
            //    txtCSAgentPerson.Text = supplier.LegalAgent;
            //    txtCSBank.Text = supplier.Bank;
            //    txtCSBankAccount.Text = supplier.BankAccount;
            //    txtCSFax.Text = supplier.Fax;
            //    txtCSLegalPerson.Text = supplier.LegalRepresentative;
            //    txtCSPhone.Text = supplier.Telephone;
            //    txtCSTaxNo.Text = supplier.TaxAccount;
            //    txtCSZipCode.Text = supplier.ZipCode;
            //}
            //if (customer != null)
            //{
            //    txtCCFullName.Text = customer.CustomerFullName;
            //    txtCCAddress.Text = customer.Address;
            //    txtCCAgentPerson.Text = customer.LegalAgent;
            //    txtCCBank.Text = customer.Bank;
            //    txtCCBankAccount.Text = customer.BankAccount;
            //    txtCCFax.Text = customer.Fax;
            //    txtCCLegalPerson.Text = customer.LegalRepresentative;
            //    txtCCPhone.Text = customer.Telephone;
            //    txtCCTaxNo.Text = customer.TaxAccount;
            //    txtCCZipCode.Text = customer.ZipCode;
            //}
            //mSalesContractDetail = SalesContractDetailBs.GetById(SelectedSalesOrder.OrderId);
            //if (mSalesContractDetail == null)
            //{
            //    return;
            //}

            //txtDetailAmountBigFormat.Text = mSalesContractDetail.AmountBigFormat;
            //txtDetailQualityStandards.Text = mSalesContractDetail.QualityStandards;
            //txtDetailShelfLife.Text = mSalesContractDetail.ShelfLife;
            //txtDetailDeliveryPlace.Text = mSalesContractDetail.DeliveryPlace;
            //txtDetailDeliveryWan.Text = mSalesContractDetail.DeliveryWan;
            //txtDetailReceivedPerson.Text = mSalesContractDetail.ReceivedPerson;
            //txtDetailReceivedPlace.Text = mSalesContractDetail.ReceivedPlace;
            //txtDetailTransportWay.Text = mSalesContractDetail.TransportWay;
            //txtDetailTransportWayOther.Text = mSalesContractDetail.TransportWayOther;
            //cmbDetailTransportAmountPayWay.Text = mSalesContractDetail.TransportAmountPayWay;
            //txtDetailPackageType.Text = mSalesContractDetail.PackageType;
            //txtDetailPackageMaterialType.Text = mSalesContractDetail.PackageMaterialType;
            //txtDetailPackageAmountPayWay.Text = mSalesContractDetail.PackageAmountPayWay;
            //txtDetailPaymentWay.Text = mSalesContractDetail.PaymentWay;
            //txtDetailPaymentWay1.Text = mSalesContractDetail.PaymentWay1;
            //txtDetailPaymentWay2.Text = mSalesContractDetail.PaymentWay2;
            //txtDetailPaymentWay3.Text = mSalesContractDetail.PaymentWay3;
            //txtDetailControversyWay.Text = mSalesContractDetail.ControversyWay;
            //txtDetailControversyWay1.Text = mSalesContractDetail.ControversyWay1;
            //txtDetailControversyWay2.Text = mSalesContractDetail.ControversyWay2;
            //txtDetailOtherRemark.Text = mSalesContractDetail.OtherRemark;
            //txtDetailCopyNumber.Text = mSalesContractDetail.CopyNumber.ToString();
            //txtDetailCopyANumber.Text = mSalesContractDetail.CopyANumber.ToString();
            //txtDetailCopyBNumber.Text = mSalesContractDetail.CopyBNumber.ToString();
        }

        private void GetContractInfo()
        {
            //if (SelectedSalesOrder == null || string.IsNullOrEmpty(SelectedSalesOrder.OrderId))
            //{
            //    return;
            //}
            //mSalesContractDetail = SalesContractDetailBs.GetById(SelectedSalesOrder.OrderId);
            //if (mSalesContractDetail == null || String.IsNullOrEmpty(mSalesContractDetail.OrderId))
            //{
            //    mSalesContractDetail = new SalesContractDetailEntity();
            //    mSalesContractDetail.OrderId = SelectedSalesOrder.OrderId;
            //}
            //mSalesContractDetail.AmountBigFormat = txtDetailAmountBigFormat.Text;
            //mSalesContractDetail.QualityStandards = txtDetailQualityStandards.Text;
            //mSalesContractDetail.ShelfLife = txtDetailShelfLife.Text;
            //mSalesContractDetail.DeliveryPlace = txtDetailDeliveryPlace.Text;
            //mSalesContractDetail.DeliveryWan = txtDetailDeliveryWan.Text;
            //mSalesContractDetail.ReceivedPerson = txtDetailReceivedPerson.Text;
            //mSalesContractDetail.ReceivedPlace = txtDetailReceivedPlace.Text;
            //mSalesContractDetail.TransportWay = txtDetailTransportWay.Text;
            //mSalesContractDetail.TransportWayOther = txtDetailTransportWayOther.Text;
            //mSalesContractDetail.TransportAmountPayWay = cmbDetailTransportAmountPayWay.Text;
            //mSalesContractDetail.PackageType = txtDetailPackageType.Text;
            //mSalesContractDetail.PackageMaterialType = txtDetailPackageMaterialType.Text;
            //mSalesContractDetail.PackageAmountPayWay = txtDetailPackageAmountPayWay.Text;
            //mSalesContractDetail.PaymentWay = txtDetailPaymentWay.Text;
            //mSalesContractDetail.PaymentWay1 = txtDetailPaymentWay1.Text;
            //mSalesContractDetail.PaymentWay2 = txtDetailPaymentWay2.Text;
            //mSalesContractDetail.PaymentWay3 = txtDetailPaymentWay3.Text;
            //mSalesContractDetail.ControversyWay = txtDetailControversyWay.Text;
            //mSalesContractDetail.ControversyWay1 = txtDetailControversyWay1.Text;
            //mSalesContractDetail.ControversyWay2 = txtDetailControversyWay2.Text;
            //mSalesContractDetail.OtherRemark = txtDetailOtherRemark.Text;
            //mSalesContractDetail.CopyNumber = CommonFunctions.ToInt32(txtDetailCopyNumber.Text);
            //mSalesContractDetail.CopyANumber = CommonFunctions.ToInt32(txtDetailCopyANumber.Text);
            //mSalesContractDetail.CopyBNumber = CommonFunctions.ToInt32(txtDetailCopyBNumber.Text);
        }

        private void SetContractInfoFieldsNew()
        {
            if (SelectedSalesOrder == null || string.IsNullOrEmpty(SelectedSalesOrder.OrderId))
            {
                return;
            }
            MstCustomerEntity supplier = MstCustomerBs.GetMstCustomerByID(SelectedSalesOrder.SupplierId);
            MstCustomerEntity customer = MstCustomerBs.GetMstCustomerByID(SelectedSalesOrder.CustomerId);
            if (supplier != null)
            {
                txtCSFullName.Text = supplier.CustomerFullName;
                txtCSAddress.Text = supplier.Address;
                txtCSAgentPerson.Text = supplier.LegalAgent;
                txtCSBank.Text = supplier.Bank;
                txtCSBankAccount.Text = supplier.BankAccount;
                txtCSFax.Text = supplier.Fax;
                txtCSLegalPerson.Text = supplier.LegalRepresentative;
                txtCSPhone.Text = supplier.Telephone;
                txtCSTaxNo.Text = supplier.TaxAccount;
                txtCSZipCode.Text = supplier.ZipCode;
            }
            if (customer != null)
            {
                txtCCFullName.Text = customer.CustomerFullName;
                txtCCAddress.Text = customer.Address;
                txtCCAgentPerson.Text = customer.LegalAgent;
                txtCCBank.Text = customer.Bank;
                txtCCBankAccount.Text = customer.BankAccount;
                txtCCFax.Text = customer.Fax;
                txtCCLegalPerson.Text = customer.LegalRepresentative;
                txtCCPhone.Text = customer.Telephone;
                txtCCTaxNo.Text = customer.TaxAccount;
                txtCCZipCode.Text = customer.ZipCode;
            }
            mSalesContractDetail = SalesContractDetailNewBs.GetById(SelectedSalesOrder.OrderId);
            if (mSalesContractDetail == null)
            {
                return;
            }

            txtContactItemTotalAmount.Text = mSalesContractDetail.TotalAmount;
            if (cboxIsTax.Checked)
            {
                txtContactItemIsTax.Text = "（含17%的增值税）";
            }
            else
            {
                txtContactItemIsTax.Text = "（不含税）";
            }
            txtContactItem2.Text = mSalesContractDetail.ContractItem2;
            txtContactItem3.Text = mSalesContractDetail.ContractItem3;
            txtContactItem4.Text = mSalesContractDetail.ContractItem4;
            txtContactItem5.Text = mSalesContractDetail.ContractItem5;
            txtContactItem6.Text = mSalesContractDetail.ContractItem6;
            txtContactItem7.Text = mSalesContractDetail.ContractItem7;
            txtContactItem8.Text = mSalesContractDetail.ContractItem8;
            txtContactItem9.Text = mSalesContractDetail.ContractItem9;
            txtContactItem10.Text = mSalesContractDetail.ContractItem10;
            txtContactItem11.Text = mSalesContractDetail.ContractItem11;
            txtContactItem12.Text = mSalesContractDetail.ContractItem12;

            dtpContractFromDate.EditValue = mSalesContractDetail.ContractFromDate;
            dtpContractEndDate.EditValue = mSalesContractDetail.ContractEndDate;
            //if (mSalesContractDetail.ContractFromDate.ToString("yyyy-MM-dd") == "1900-01-01" ||
            //    mSalesContractDetail.ContractFromDate.ToString("yyyy-MM-dd") == "0001-01-01")
            //{
            //    dtpContractFromDate.Checked = false;
            //}
            //else
            //{
            //    dtpContractFromDate.Value = mSalesContractDetail.ContractFromDate;
            //    dtpContractFromDate.Checked = true;
            //}
            //if (mSalesContractDetail.ContractEndDate.ToString("yyyy-MM-dd") == "1900-01-01" ||
            //    mSalesContractDetail.ContractEndDate.ToString("yyyy-MM-dd") == "0001-01-01")
            //{
            //    dtpContractEndDate.Checked = false;
            //}
            //else
            //{
            //    dtpContractEndDate.Value = mSalesContractDetail.ContractEndDate;
            //    dtpContractEndDate.Checked = true;
            //}
        }

        private void GetContractInfoNew()
        {
            if (SelectedSalesOrder == null || string.IsNullOrEmpty(SelectedSalesOrder.OrderId))
            {
                return;
            }
            mSalesContractDetail = SalesContractDetailNewBs.GetById(SelectedSalesOrder.OrderId);
            if (mSalesContractDetail == null || String.IsNullOrEmpty(mSalesContractDetail.OrderId))
            {
                mSalesContractDetail = new SalesContractDetailNewEntity();
                mSalesContractDetail.OrderId = SelectedSalesOrder.OrderId;
            }
            mSalesContractDetail.TotalAmount = txtContactItemTotalAmount.Text;
            mSalesContractDetail.ContractItem2 = txtContactItem2.Text;
            mSalesContractDetail.ContractItem3 = txtContactItem3.Text;
            mSalesContractDetail.ContractItem4 = txtContactItem4.Text;
            mSalesContractDetail.ContractItem5 = txtContactItem5.Text;
            mSalesContractDetail.ContractItem6 = txtContactItem6.Text;
            mSalesContractDetail.ContractItem7 = txtContactItem7.Text;
            mSalesContractDetail.ContractItem8 = txtContactItem8.Text;
            mSalesContractDetail.ContractItem9 = txtContactItem9.Text;
            mSalesContractDetail.ContractItem10 = txtContactItem10.Text;
            mSalesContractDetail.ContractItem11 = txtContactItem11.Text;
            mSalesContractDetail.ContractItem12 = txtContactItem12.Text;

            if (dtpContractFromDate.EditValue != null)
            {
                mSalesContractDetail.ContractFromDate = ((DateTime)dtpContractFromDate.EditValue);
            }
            if (dtpContractEndDate.EditValue != null)
            {
                mSalesContractDetail.ContractEndDate = ((DateTime)dtpContractEndDate.EditValue);
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindComboBox();
            SetFields(true);
            SetDataGridDetailByApplicationItems();
            SetFieldsByApplication();
            if (SelectedSalesOrder != null && string.IsNullOrEmpty(SelectedSalesOrder.Attachment) == false)
            {
                btnDownload.Enabled = true;
            }
            else
            {
                btnDownload.Enabled = false;
            }
            if (ThisActionType != ActionType.New)
            {
                SetContractInfoFieldsNew();
            }
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedSalesOrder = new SalesOrderEntity();
                SelectedSalesOrder.OrderId = Guid.NewGuid().ToString();
                SetFields(true);
            }
        }

        protected override void Click_Approve()
        {
            if (SelectedSalesOrder == null)
            {
                return;
            }
            SelectedSalesOrder.Status = SalesStatus.SALES03.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Reject()
        {
            if (SelectedSalesOrder == null)
            {
                return;
            }
            SelectedSalesOrder.Status = SalesStatus.SALES04.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtQuoteOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainSalesQuoteOrderQuery frm = new frmMaintainSalesQuoteOrderQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedQuoteOrder != null)
            {
                txtQuoteOrder.Text = frm.SelectedQuoteOrder.QuoteOrderCode;
                txtQuoteOrder.Tag = frm.SelectedQuoteOrder;

                SetSalesOrderByQuoteOrder(frm.SelectedQuoteOrder);
            }
            else
            {
                txtQuoteOrder.Text = "";
                txtQuoteOrder.Tag = null;
            }
        }

        private void txtSupplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainSupplierQuery frm = new frmMaintainSupplierQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedSupplier != null)
            {
                txtSupplier.Text = frm.SelectedSupplier.SupplierName;
                txtSupplier.Tag = frm.SelectedSupplier;

                UICommonFunctions.BindSupplierContactCombobox(cmbSupplierContact, frm.SelectedSupplier.SupplierId, false);
            }
            else
            {
                txtSupplier.Text = "";
                txtSupplier.Tag = null;

                UICommonFunctions.BindSupplierContactCombobox(cmbSupplierContact, "", false);
                txtSupplierContactPhone.Text = "";
            }
        }

        private void txtCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtOrderPerson.Tag == null || txtOrderPerson.Tag.GetType() != typeof(MstPersonEntity))
            {
                MessageBox.Show("请先选择业务员！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainCustomerQuery frm = new frmMaintainCustomerQuery((MstPersonEntity)txtOrderPerson.Tag);
            frm.ShowAllCustomer = true;
            ResetContactColumn();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedCustomer != null)
            {
                SetFieldsByCustomer(frm.SelectedCustomer);
            }
            else
            {
                SetFieldsByCustomer(null);
            }
        }

        private void txtOrderPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtOrderPerson.Text = frm.SelectedPerson.NameCn;
                txtOrderPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtOrderPerson.Text = "";
                txtOrderPerson.Tag = null;
            }
        }

        private DataRow drItemSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drItemSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            DataRow dr = dt.NewRow();
            dr["ORDER_ITEM_ID"] = Guid.NewGuid().ToString();
            dr["ORDER_ID"] = SelectedSalesOrder.OrderId;
            dr["TAX_RATE"] = 0.17;
            dt.Rows.Add(dr);
        }

        private void tsmDelLine_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            if (drItemSelected == null)
            {
                return;
            }

            if (drItemSelected.RowState != DataRowState.Added)
            {
                SalesOrderItemEntity entity = new SalesOrderItemEntity(drItemSelected);
                DeleteList.Add(entity);
            }
            DataTable dt = gvMain.DataSource as DataTable;
            dt.Rows.Remove(drItemSelected);
            ResetTotalAmount();
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (drItemSelected == null)
            {
                return;
            }
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                drItemSelected["PRODUCT_ID"] = frm.SelectedProduct.ProductId;
                drItemSelected["PRODUCT_CODE"] = frm.SelectedProduct.ProductCode;
                drItemSelected["SUGGEST_PRICE"] = frm.SelectedProduct.SuggestPrice;
                drItemSelected["PRODUCT_SPEC_IN"] = frm.SelectedProduct.ProductSpecIn;
                drItemSelected["PRODUCT_SPEC_OUT"] = frm.SelectedProduct.ProductSpecOut;
                drItemSelected["MATERIAL"] = frm.SelectedProduct.Material;
                drItemSelected["DIAMETER_OUT"] = frm.SelectedProduct.DiameterOut;
                drItemSelected["DIAMETER_IN"] = frm.SelectedProduct.DiameterIn;
                drItemSelected["LENGTH"] = frm.SelectedProduct.Length;
                drItemSelected["UNIT"] = frm.SelectedProduct.Unit;
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.Equals("QTY") || e.Column.FieldName.Equals("PRICE_NO_TAX"))
            {
                ResetTotalAmount();
            }
        }

        private void cboxIsTax_CheckedChanged(object sender, EventArgs e)
        {
            if (cboxIsTax.Checked)
            {
                gridView1.Columns["PRICE_NO_TAX"].Caption = "单价（含税）";
                gridView1.Columns["TOTAL_AMOUNT"].Caption = "小计（含税）";
                ResetTax();
            }
            else
            {
                gridView1.Columns["PRICE_NO_TAX"].Caption = "单价";
                gridView1.Columns["TOTAL_AMOUNT"].Caption = "小计";
                ResetTax();
            }
            //lblTax.Visible = cboxIsTax.Checked;
        }

        private void cmbSupplierContact_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSupplierContact.SelectedItem != null && cmbSupplierContact.SelectedItem.GetType() == typeof(MstSupplierContactEntity))
            {
                MstSupplierContactEntity entity = (MstSupplierContactEntity)cmbSupplierContact.SelectedItem;
                if (entity != null)
                {
                    txtSupplierContactPhone.Text = entity.ContactOfficePhone;
                }
            }
        }

        private void cmbCustomerContact_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCustomerContact.SelectedItem != null)
            {
                MstCustomerContactEntity entity = (MstCustomerContactEntity)cmbCustomerContact.SelectedItem;
                if (entity != null)
                {
                    txtCustomerContactPhone.Text = entity.ContactMobilephone;
                }
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.View)
            {
                return;
            }
            if (ThisActionType == ActionType.New || SelectedSalesOrder == null)
            {
                MessageBox.Show("请先保存后再上传文件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            OpenFileDialog fd = new OpenFileDialog();
            fd.Multiselect = false;
            fd.Filter = "JPG文件|*.jpg|PNG文件|*.png";
            if (fd.ShowDialog() == DialogResult.OK)
            {
             
                Cursor = Cursors.WaitCursor;
                bool result = UploadAttached(fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                {
                    MessageBox.Show("上传成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.New)
            {
                MessageBox.Show("没有可下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (string.IsNullOrEmpty(SelectedSalesOrder.Attachment))
            {
                MessageBox.Show("没有找到可以下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog fd = new SaveFileDialog();
            fd.FileName = SelectedSalesOrder.Attachment;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = DownloadAttached(fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                {
                    MessageBox.Show("下载成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        #endregion

        private void btnAppQuery_Click(object sender, EventArgs e)
        {
            frmMaintainProductPlanApplicationQuery frm = new frmMaintainProductPlanApplicationQuery(true);
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK && frm.selectedProdPlanAppList != null && frm.selectedProdPlanAppList.Count > 0)
            {
                lboxAppOrder.Tag = frm.selectedProdPlanAppList;
                lboxAppOrder.Items.Clear();
                foreach (SalesProdPlanApplicationEntity entity in frm.selectedProdPlanAppList)
                {
                    if (entity == null)
                    {
                        continue;
                    }
                    lboxAppOrder.Items.Add(entity.ApplicationCode);
                }
            }
            else
            {
                lboxAppOrder.Tag = null;
                lboxAppOrder.Items.Clear();
            }
            SetDataGridDetailByListBox();
        }

        private void frmMaintainSalesOrder_Load(object sender, EventArgs e)
        {
            //dtpDeliveryDate.EditValue = "";
        }

        private void repositoryItemDateEdit1_Click(object sender, EventArgs e)
        {

        }

       

    }
}
